package com.promise.jokerdream.work.faction

import com.promise.jokerdream.database.entity.FactionFeedDemoGameConfigEntity
import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.model.faction.FactionFeedDemoMapping
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 帮派供奉工作
class FactionFeedDemoWork(
    private val config: FactionFeedDemoGameConfigEntity,
    uin: String
): BaseWork(uin) {
    
    private val gameApi = GameApi.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.getInstance(AppContext.get()) }
    
    override val name: String
        get() = "帮派供奉"
    
    override suspend fun executeWork(): WorkResult {
        return try {
            // 1. 查询活跃度信息，检查是否已供奉
            val livenessResult = gameApi.queryLiveness()
            livenessResult.foldWithApiException(
                onSuccess = { response ->
                    if (response.feedDemo == 0) {
                        // 未供奉，检查配置中是否有供奉物品名称
                        if (config.feedItemName.isNotEmpty()) {
                            // 根据物品名称获取ID
                            val itemId = getItemIdByName(config.feedItemName)
                            if (itemId != null) {
                                // 执行供奉
                                val feedResult = gameApi.feedDemo(itemId)
                                feedResult.foldWithApiException(
                                    onSuccess = { feedResponse ->
                                        historyManager.addHistory(name, feedResponse.getDescription())
                                    },
                                    onFailure = { code, msg ->
                                        historyManager.addHistory(name, msg, code)
                                    }
                                )
                            } else {
                                historyManager.addHistory(name, "你没有该物品: ${config.feedItemName}")
                            }
                        }
                    }
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                }
            )
            
            WorkResult.Success
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
    
    /**
     * 根据物品名称获取ID
     * 1、优先从FactionFeedDemoMapping里找
     * 2、如果没有则通过bagGoods请求，BagGoodsPCResponse的BagGoods遍历找
     */
    private suspend fun getItemIdByName(itemName: String): Int? {
        // 1、优先从FactionFeedDemoMapping里找
        val mappingId = FactionFeedDemoMapping.getIdByName(itemName)
        if (mappingId != null) {
            return mappingId
        }
        
        // 2、如果没有则通过bagGoods请求查找
        return try {
            val bagResult = gameApi.queryBagGoods(uin)
            bagResult.foldWithApiException(
                onSuccess = { response ->
                    // 在背包物品中查找匹配的物品
                    response.bag.find { it.name == itemName }?.id
                },
                onFailure = { _, _ ->
                    null
                }
            )
        } catch (e: Exception) {
            null
        }
    }
}